/**
 * @Title: FileManager.java
 * @Prject: p2p-person
 * @Package: com.lc.web.fastdfs
 * @Description:
 * @author: CJNusan
 * @date: 2017年11月8日 下午9:55:35
 * @version: V1.0
 */
package com.company.project.config.file.fastdfs;

import org.csource.common.NameValuePair;
import org.csource.fastdfs.*;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;

import java.io.File;

/**
 * @Description: FastDFS Java客户端工具类
 * @author: CJNusun
 * @date: 2018年09月01日 下午9:55:35
 */
public class FileManager implements FileManagerConfig {

    /**
     *
     */
    private static final long serialVersionUID = 1L;

    private static TrackerClient trackerClient;
    private static TrackerServer trackerServer;
    private static StorageServer storageServer;
    private static StorageClient storageClient;

    static {
        try {
            String classPath = new File(FileManager.class.getResource(File.separator).getFile()).getCanonicalPath();

            String fdfsClientConfigFilePath = classPath + File.separator + CLIENT_CONFIG_FILE;
            ClientGlobal.init(fdfsClientConfigFilePath);

            trackerClient = new TrackerClient();
            trackerServer = trackerClient.getConnection();
            storageServer = trackerClient.getStoreStorage(trackerServer);
            storageClient = new StorageClient(trackerServer, storageServer);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * <strong>方法概要： 文件上传</strong> <br>
     *
     * @param file appendix
     * @return fileAbsolutePath
     * @author CJNusun
     */
    public static String upload(FastDFSFile file, NameValuePair[] valuePairs) {
        String[] uploadResults = {"null", "error.log"};
        try {
            uploadResults = storageClient.upload_file(file.getContent(), file.getExt(), valuePairs);
        } catch (Exception e) {
            e.printStackTrace();
        }
        String groupName = uploadResults[0];
        String remoteFileName = uploadResults[1];

        String fileAbsolutePath = PROTOCOL
                + TRACKER_NGNIX_ADDR
                //+ trackerServer.getInetSocketAddress().getHostName()
                + ":" + TRACKER_NGNIX_PORT
                + SEPARATOR + groupName
                + SEPARATOR + remoteFileName;
        return fileAbsolutePath;
    }

    /**
     * 方法概要： 文件下载
     * 创建时间： 2016-9-26 上午10:28:21
     *
     * @author CJNusun
     */
    public static ResponseEntity<byte[]> download(String groupName,
                                                  String remoteFileName, String specFileName) {
        byte[] content = null;
        HttpHeaders headers = new HttpHeaders();
        try {
            content = storageClient.download_file(groupName, remoteFileName);
            headers.setContentDispositionFormData("attachment", new String(specFileName.getBytes("UTF-8"), "iso-8859-1"));
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return new ResponseEntity(content, headers, HttpStatus.CREATED);
    }

    /**
     * 删除文件
     *
     * @return 删除失败返回-1，正常返回0 已删除返回2
     */
    public static int deleteFile(String groupName, String remoteFileName) {
        try {
            FileInfo fileInfo = storageClient.query_file_info(groupName, remoteFileName);

            return storageClient.delete_file(groupName, remoteFileName);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return -1;
    }

    /**
     * 清除文件
     *
     * @return 删除失败返回-1，否则返回0
     */
    public static int truncateFile(String groupName, String remoteFileName) {
        try {
            storageClient.query_file_info(groupName, remoteFileName);
            return storageClient.truncate_file(groupName, remoteFileName);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return -1;
    }

}
